<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="clearfix">
          <span>飞行执照管理</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">
            <el-icon><Back /></el-icon> 返回
          </el-button>
        </div>
      </template>
      <el-button type="primary" @click="handleAdd">新增执照</el-button>
      
      <el-table v-loading="loading" :data="licenseList" style="margin-bottom: 20px;">
        <el-table-column label="执照类型" prop="licenseType" align="center">
          <template #default="scope">
            <dict-tag :options="licenseTypeOptions" :value="scope.row.licenseType"/>
          </template>
        </el-table-column>
        <el-table-column label="执照编号" prop="licenseNumber" align="center" />
        <el-table-column label="到期日期" prop="expiryDate" align="center" />
        <el-table-column label="执照图片" align="center">
          <template #default="scope">
            <el-image 
              style="width: 50px; height: 50px"
              :src="getImageUrl(scope.row.imagePath)"
              fit="cover"
              :preview-src-list="scope.row.imagePath ? [getImageUrl(scope.row.imagePath)] : []"
              :preview-teleported="true"
              :initial-index="0"
              preview-class="license-preview"
              :z-index="3000">
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="text" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="text" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

  

      <!-- 添加或修改执照对话框 -->
      <el-dialog :title="title" v-model="open" width="500px" append-to-body>
        <el-form ref="licenseFormRef" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="执照类型" prop="licenseType">
            <el-select v-model="form.licenseType" placeholder="请选择执照类型">
              <el-option
                v-for="dict in licenseTypeOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="执照编号" prop="licenseNumber">
            <el-input v-model="form.licenseNumber" placeholder="请输入执照编号" />
          </el-form-item>
          <el-form-item label="到期日期" prop="expiryDate">
            <el-date-picker
              v-model="form.expiryDate"
              type="date"
              placeholder="选择到期日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="执照图片">
            <el-upload
              class="license-uploader"
              action="#"
              :http-request="requestUpload"
              :show-file-list="false"
              :before-upload="beforeUpload"
              accept="image/jpeg,image/png,image/jpg"
            >
              <img v-if="form.imagePath" :src="getImageUrl(form.imagePath)" class="license-image" />
              <el-icon v-else class="license-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="el-upload__tip">支持 jpg、png 格式，且不超过 20MB</div>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { getCurrentInstance, ref, reactive, toRefs, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Back, Picture } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import request from '@/utils/request';
import { getToken } from '@/utils/auth';

const router = useRouter();
const { proxy } = getCurrentInstance();
const open = ref(false);
const loading = ref(true);
const title = ref("");
const licenseList = ref([]);
const licenseFormRef = ref(null);

const licenseTypeOptions = [
  { value: "UTC", label: "UTC" },
  { value: "ASFC", label: "ASFC" },
  { value: "CAAC", label: "CAAC" }
];

const data = reactive({
  form: {
    licenseId: undefined,
    licenseType: undefined,
    licenseNumber: undefined,
    expiryDate: undefined,
    imagePath: undefined
  },
  rules: {
    licenseType: [{ required: true, message: "执照类型不能为空", trigger: "change" }],
    licenseNumber: [{ required: true, message: "执照编号不能为空", trigger: "blur" }],
    expiryDate: [{ required: true, message: "到期日期不能为空", trigger: "change" }]
  }
});

// 添加上传状态
const uploadStatus = ref({
  uploading: false,
  preview: null
});

const { form, rules } = toRefs(data);

/** 返回个人中心 */
function goBack() {
  router.push({ path: '/user/profile' });
}

/** 查询执照列表 */
function getList() {
  loading.value = true;
  request({
    url: '/system/user/profile/license/list',
    method: 'get'
  }).then(response => {
    licenseList.value = response.data;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  try {
    form.value = {
      licenseId: undefined,
      licenseType: undefined,
      licenseNumber: undefined,
      expiryDate: undefined,
      imagePath: undefined
    };
    if (licenseFormRef.value) {
      licenseFormRef.value.resetFields();
    }
  } catch (error) {
    console.error('重置表单时出错:', error);
  }
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加执照";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  try {
    reset();
    form.value = {
      licenseId: row.licenseId,
      licenseType: row.licenseType,
      licenseNumber: row.licenseNumber,
      expiryDate: row.expiryDate,
      imagePath: row.imagePath
    };
    open.value = true;
    title.value = "修改执照";
  } catch (error) {
    console.error('修改操作时出错:', error);
    ElMessage.error('修改操作失败，请重试');
  }
}

/** 提交按钮 */
function submitForm() {
  if (!licenseFormRef.value) return;
  
  licenseFormRef.value.validate(valid => {
    if (valid) {
      // 检查是否正在上传
      if (uploadStatus.value.uploading) {
        ElMessage.warning('请等待图片上传完成');
        return;
      }

      // 检查是否是预览图片
      if (form.value.imagePath && form.value.imagePath.startsWith('data:')) {
        ElMessage.warning('请等待图片上传完成');
        return;
      }

      if (form.value.licenseId != undefined) {
        request({
          url: '/system/user/profile/license',
          method: 'put',
          data: form.value
        }).then(response => {
          if (response.code === 200) {
            ElMessage.success("修改成功");
            open.value = false;
            getList();
          } else {
            ElMessage.error(response.msg || "修改失败");
          }
        });
      } else {
        request({
          url: '/system/user/profile/license',
          method: 'post',
          data: form.value
        }).then(response => {
          if (response.code === 200) {
            ElMessage.success("新增成功");
            open.value = false;
            getList();
          } else {
            ElMessage.error(response.msg || "新增失败");
          }
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  ElMessageBox.confirm('是否确认删除该执照？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return request({
      url: '/system/user/profile/license/' + row.licenseId,
      method: 'delete'
    });
  }).then(() => {
    getList();
    ElMessage.success("删除成功");
  }).catch(() => {});
}

/** 覆盖默认上传行为 */
function requestUpload(options) {
  const file = options.file;
  const formData = new FormData();
  formData.append("file", file);
  
  // 设置上传状态
  uploadStatus.value.uploading = true;

  // 使用 request 方法上传
  request({
    url: '/system/user/profile/license/image',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(res => {
    if (res.code === 200) {
      // 上传成功，设置图片路径
      form.value.imagePath = res.imagePath;
      ElMessage.success("上传成功");
    } else {
      // 上传失败，恢复预览图
      form.value.imagePath = uploadStatus.value.preview;
      ElMessage.error(res.msg || "上传失败");
    }
  }).catch(error => {
    console.error("上传失败:", error);
    form.value.imagePath = uploadStatus.value.preview;
    ElMessage.error("上传失败，请重试");
  }).finally(() => {
    uploadStatus.value.uploading = false;
  });
}

/** 获取图片完整URL */
function getImageUrl(path) {
  if (!path) return '';
  if (path.startsWith('data:')) return path; // 处理 base64 预览图片
  if (path.startsWith('http')) return path;  // 处理完整 URL
  // 移除路径中可能存在的多余斜杠
  const cleanPath = path.replace(/^\/+/, '').replace(/\/+/g, '/');
  return import.meta.env.VITE_APP_BASE_API + cleanPath;
}

/** 上传前图片格式校验 */
function beforeUpload(file) {
  const isImage = file.type.indexOf("image/") > -1;
  if (!isImage) {
    ElMessage.error("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
    return false;
  } 
  const isLt2M = file.size / 1024 / 1024 < 20;
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 20MB!');
    return false;
  }

  // 保存当前图片路径作为备份
  uploadStatus.value.preview = form.value.imagePath;

  // 显示预览图
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {
    form.value.imagePath = reader.result;
  };
  return true;
}

onMounted(() => {
  getList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.license-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}
.license-uploader:hover {
  border-color: #409eff;
}
.license-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}
.license-image {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}
.image-slot .el-icon {
  font-size: 24px;
}

:deep(.el-image-viewer__wrapper) {
  z-index: 3000 !important;
}

:deep(.el-image-viewer__mask) {
  z-index: 2999 !important;
}

:deep(.license-preview) {
  z-index: 3000;
}
</style> 